package str;

/**
 * leet-code(394) 字符串解码
 *
 * @auther yang
 * @date 2022/4/26 9:09
 */
public class DecodeString {

    public static void main(String[] args) {
        String s = "100[leetcode]";
        System.out.println(decodeString(s));
    }

    public static String decodeString(String s) {
        Item[] stack = new Item[s.length()];
        int p = -1;

        int num = 0;
        String result = "";                     // 实时记录当前可以提取出来的字符串

        for (int i = 0; i < s.length(); ++i) {
            char ch = s.charAt(i);
            if (Character.isDigit(ch)) {
                // 必须这样写, 出现双位数和三位数的情况
                num = 10 * num + Integer.parseInt(String.valueOf(ch));
            } else if (ch == '[') {
                stack[++p] = new Item(result, num);
                result = "";
                num = 0;
            } else if (ch == ']') {
                if (p < 0) throw new IllegalArgumentException("字符串: " + s + "格式不正确");
                Item top = stack[p--];
                StringBuilder builder = new StringBuilder();
                for (int j = 0; j < top.n; ++j) builder.append(result);
                result = top.str + builder.toString();
            } else {
                result += ch;
            }
        }
        return result;
    }

    private static class Item {

        /**
         * 记录左括号之前的字符串
         */
        protected String str;

        /**
         * 左括号外的上一个数字
         */
        protected Integer n;

        public Item(String str, Integer n) {
            this.str = str;
            this.n = n;
        }
    }

}
